package com.gonsin.gview.example.utils;

import com.gonsin.base.GPageRequest;
import com.gonsin.base.GPageResult;
import com.gonsin.gview.example.bean.GroupBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.util.Arrays;
import java.util.List;

public class PageableUtils {

    /**
     * 将pagepo转换为JPA 的pageable
     * @param GPageRequest
     * @return
     */
    public static Pageable toPageable(GPageRequest GPageRequest){
        if(GPageRequest == null){
            return PageRequest.of(0, Integer.MAX_VALUE);
        }
        Sort sort = null;
//        if(StringUtils.isEmpty(GPageRequest.getSort())){
//            sort = (StringUtils.isEmpty(GPageRequest.getSortBy()) || GPageRequest.getSortDirection() == null) ? Sort.unsorted()
//                    : Sort.by(GPageRequest.getSortDirection() == 1 ? Sort.Direction.DESC : Sort.Direction.ASC, GPageRequest.getSortBy());
//        } else {
        if(StringUtils.isNotEmpty(GPageRequest.getSort())){
            List<String> sortItems = Arrays.asList(GPageRequest.getSort().split(","));
            for(int i = 0; i < sortItems.size(); i++){
                String item = sortItems.get(i);
                if(!item.startsWith("+") && !item.startsWith("-")){
                    continue;
                }
                String sortBy = item.substring(1);
                Sort.Direction sortDirection = GPageRequest.getSort().startsWith("+") ? Sort.Direction.ASC : Sort.Direction.DESC;
                if(sort == null){
                    sort = Sort.by(sortDirection, sortBy);
                } else {
                    sort = sort.and(Sort.by(sortDirection, sortBy));
                }
            }
        }

        if(sort == null){
            sort = Sort.unsorted();
        }
        Pageable pageable = PageRequest.of(GPageRequest.getPage(), GPageRequest.getCount(), sort);
        return pageable;
    }


    /**
     * 翻页查询结果转换
     */
    public static <T> GPageResult<T> toGPageResult(Page<T> data) {
        GPageResult<T> result = new GPageResult<>();
        result.setData(data.getContent());
        result.setPage(data.getNumber());
        result.setPageCount(data.getTotalPages());
        result.setCount(data.getNumberOfElements());
        return result;
    }
}
